package official

// examples
// https://github.com/gin-gonic/gin/blob/master/examples/basic/main.go
// gin home examples
// https://godoc.org/github.com/gin-gonic/gin#pkg-constants

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

var DB = make(map[string]string)

func Httphost()  {
	r := gin.Default()

	r.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "pong!")
	})

	r.GET("/user/:name", func(c *gin.Context) {
		user := c.Params.ByName("name")
		val , ok := DB[user]
		if ok {
			c.JSON(http.StatusOK, gin.H{
				"user" : user,
				"value" : val,
			})
		}else{
			c.JSON(http.StatusOK, gin.H{
				"user" : user,
				"value" : "no value!",
			})
		}
	})

	authorized := r.Group("/", gin.BasicAuth(
		gin.Accounts{
			"foo" : "bar",
			"pass" : "123",
		})
	)

	authorized.POST("admin", func(c *gin.Context) {
		user := c.MustGet(gin.AuthUserKey).(string)
		var json struct{
			value string `json:"value" binding:"required"`
		}

		if c.Bind(&json) {
			DB[user] = json.value
			c.JSON(http.StatusOK, gin.H{
				"status" : "ok",
			})
		}
	})
}
